﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using Game.Global.Buffer;

namespace Game
{
	public class CellsView : MonoBehaviour 
	{
        public static CellsView instance
        {
            get;
            private set;
        }

        /// <summary>
        /// 细胞的预制体
        /// </summary>
        [SerializeField]GameObject m_cellPrefab;

        /// <summary>
        /// 细胞物体的缓存
        /// </summary>
        GameObjBuffer m_cellObjsBuffer;

        /// <summary>
        /// 用于管理场上的细胞物体
        /// </summary>
        Dictionary<IntVector2, GameObject> m_cellsInTableView = new Dictionary<IntVector2, GameObject>();

        /// <summary>
        /// 用于管理CellTable的视图表现
        /// </summary>
        Transform m_tableViewTransform;

		void Awake () 
		{
            instance = this;
            m_tableViewTransform = this.transform;
		}
		
		//---------------------------------------------------------------------------
		//				Public area
		//---------------------------------------------------------------------------
		#region Public area
        public void Init(int tableLength)
        {
            m_cellObjsBuffer = new GameObjBuffer (m_cellPrefab, tableLength);

            ResetView(tableLength);
        }

        /// <summary>
        /// 重置视图：设定棋盘大小等
        /// </summary>
        /// <param name="tableLength">棋盘边长，非正数则表示采用之前的大小</param>
        public void ResetView(int tableLength = 0)
        {
            //--如果给定了Table长度，则需要重新设置棋盘格视图、镜头等：
            if (tableLength > 0)
            {
                //--重设棋盘格贴图：
                m_tableViewTransform.GetComponentInChildren<Renderer>().material.SetTextureScale("_MainTex", new Vector2(tableLength, tableLength));
                //--重置棋盘大小：
                m_tableViewTransform.transform.localScale = new Vector3(tableLength, 1, tableLength);
                
            }
        }

        /// <summary>
        /// 将一个细胞物体放在该位置
        /// </summary>
        public void PutCellObjAt(IntVector2 bornPos)
        {
            //Debug.Log("put in view "+bornPos);
            //--获得一个可用的细胞物体
            GameObject obj = m_cellObjsBuffer.PopObjectBuffered();
            m_cellsInTableView[bornPos] = obj;

            obj.transform.position = new Vector3(bornPos.x, 0, bornPos.y);
        }

        /// <summary>
        /// 将一个细胞物体从该位置移除
        /// </summary>
        public void ClearCellObjAt(IntVector2 diePos)
        {
            //Debug.Log("Remove in view at "+diePos);
            //--归还细胞物体
            m_cellObjsBuffer.PushObject(m_cellsInTableView[diePos]);
        }

		#endregion

		//---------------------------------------------------------------------------
		//				Private area
		//---------------------------------------------------------------------------
		#region Private area
		#endregion
	}
}